package ai.assist.common.businesss.service;

import lombok.extern.slf4j.Slf4j;

/**
 * @author hui
 * @Date 2025/1/20 16:04
 **/
@Slf4j
public class HighCpuUsage {

    public static void run(Integer numThreads, Integer duration) {
        duration = duration == null ? 60 : duration; // 默认持续时间，单位为秒
        numThreads = numThreads == null ? Runtime.getRuntime().availableProcessors() - 2 : numThreads; // 默认线程数为 CPU 核心数
        log.info("开始提高 CPU 使用率，使用 " + numThreads + " 个线程，持续 " + duration + " 秒...");
        // 创建并启动多个线程
        for (int i = 0; i < numThreads; i++) {
            Thread thread = new Thread(new CpuIntensiveTask(duration));
            thread.start();
        }
    }

    static class CpuIntensiveTask implements Runnable {
        private final int duration;

        public CpuIntensiveTask(int duration) {
            this.duration = duration;
        }

        @Override
        public void run() {
            long endTime = System.currentTimeMillis() + duration * 1000L;
            while (System.currentTimeMillis() < endTime) {
                Math.sqrt(123456789.0);
            }
        }
    }

}
